// Physical memory allocator, for user processes,
// kernel stacks, page-table pages,
// and pipe buffers. Allocates whole 4096-byte pages.


#include "include/types.h"
#include "include/param.h"
#include "include/memlayout.h"
#include "include/riscv.h"
#include "include/defs.h"
#include "include/spinlock.h"

void freerange(void *pa_start, void *pa_end);

extern char kernel_end[]; // first address after kernel.

struct run {
  struct run *next;
};

struct {
  struct spinlock lock;
  struct run *freelist;
} kmem;

struct {
  struct spinlock lock;
  uint counter[(PHYSTOP - KERNBASE) / PGSIZE];
} refcnt;

uint64
pgindex(uint64 pa){
  return (pa - KERNBASE) / PGSIZE;
}

void
acquire_refcnt(){
  acquire(&refcnt.lock);
}

void
release_refcnt(){
  release(&refcnt.lock);
}

void
refcnt_setter(uint64 pa, int n){
  refcnt.counter[pgindex((uint64)pa)] = n;
}

uint
refcnt_getter(uint64 pa){
  return refcnt.counter[pgindex(pa)];
}

void
refcnt_incr(uint64 pa, int n){
  acquire(&refcnt.lock);
  refcnt.counter[pgindex(pa)] += n;
  release(&refcnt.lock);
}

void
kinit()
{
  initlock(&kmem.lock, "kmem");
  // printf("kernel_end: %p, phystop: %p\n", kernel_end, (void*)PHYSTOP);
  freerange(kernel_end, (void*)PHYSTOP);
  #ifdef DEBUG
  printf("kinit\n");
  #endif
}

void
freerange(void *pa_start, void *pa_end)
{
  char *p;
  p = (char*)PGROUNDUP((uint64)pa_start);
  for(; p + PGSIZE <= (char*)pa_end; p += PGSIZE) {
    refcnt.counter[pgindex((uint64)p)] = 0;
    kfree(p);
  }
}

// Free the page of physical memory pointed at by v,
// which normally should have been returned by a
// call to kalloc().  (The exception is when
// initializing the allocator; see kinit above.)
void
kfree(void *pa)
{
  struct run *r;
  
  if(((uint64)pa % PGSIZE) != 0 || (char*)pa < kernel_end || (uint64)pa >= PHYSTOP)
    panic("kfree");

  
  acquire_refcnt();
  int index = pgindex((uint64)pa);

  // only decrement ref count if ref > 1
  if (refcnt.counter[index] > 1) {
    refcnt.counter[index] -= 1;
    release_refcnt();
    return;
  }
  
  // Fill with junk to catch dangling refs.
  memset(pa, 1, PGSIZE);
  // free mem when ref count = 1
  refcnt.counter[index] = 0;
  release_refcnt();
  r = (struct run*)pa;

  acquire(&kmem.lock);
  r->next = kmem.freelist;
  kmem.freelist = r;
  release(&kmem.lock);
}

// Allocate one 4096-byte page of physical memory.
// Returns a pointer that the kernel can use.
// Returns 0 if the memory cannot be allocated.
void *
kalloc(void)
{
  struct run *r;

  acquire(&kmem.lock);
  r = kmem.freelist;
  if(r)
    kmem.freelist = r->next;
  release(&kmem.lock);

  if(r) {
    memset((char*)r, 5, PGSIZE); // fill with junk
    acquire_refcnt();
    refcnt.counter[pgindex((uint64)r)] = 1;
    release_refcnt();
  }
  return (void*)r;
}

uint64
freemem_amount(void)
{
  struct run *r;
  uint64 amount = 0;

  // acquire(&kmem.lock);
  r = kmem.freelist;
  while (r) {
    amount++;
    r = r->next;
  }
  // release(&kmem.lock);

  return amount * PGSIZE;
}
